package com.zhenbao.system.filter;

import com.zhenbao.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 过滤器
 */
@Component
public class AuthorizeFilter implements GlobalFilter,Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求的对象
        ServerHttpRequest request = exchange.getRequest();
        //2.响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3.当前请求是否是登录请求，如果是就放行
        if (request.getURI().getPath().contains("/admin/login")){
            //放行
            return chain.filter(exchange);
        }
        //4.获取当前所有请求头信息
        HttpHeaders headers = request.getHeaders();
        //5.获取gwt的令牌信息
        String token = headers.getFirst("token");
        //6.判断当前令牌是否存在
        if (StringUtils.isEmpty(token)){
            //6.1如果不存在返回错误信息给客户端
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.2如果存在解析gwt令牌，判断该令牌是否合法。如果令牌不合法向客户端返回错误信息
        try {
            JwtUtil.parseJWT(token);
        }catch (Exception e){
            e.printStackTrace();
            //解析失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.3如果令牌合法，则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
